package com.cn.activitiNSV.controller.activiti;

import com.cn.activitiNSV.entity.ProcessFlow;
import com.cn.activitiNSV.entity.TaskNSEntity;
import com.cn.activitiNSV.util.RestServiceController;
import com.cn.activitiNSV.util.Result;
import com.cn.activitiNSV.util.Status;
import com.cn.activitiNSV.util.ToWeb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;


import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 模型管理
 */
@Controller
@RequestMapping("/modeler")
@CrossOrigin
public class ModelerController implements RestServiceController<Model, String> {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    HistoryService historyService;

    /**
     * 新建一个空模型
     *
     * @return
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    @GetMapping("newModel")
    @ResponseBody
    public Map<String, Object> newModel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //初始化一个空模型
        Model model = repositoryService.newModel();

        //设置一些默认信息
        String name = "质检工作流程图";
        String description = "";
        int revision = 1;
        String key = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "" + (Math.random() * 100);

        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
        modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
        modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);

        model.setName(name);
        model.setKey(key);
        model.setMetaInfo(modelNode.toString());

        repositoryService.saveModel(model);
        String id = model.getId();

        //完善ModelEditorSource
        ObjectNode editorNode = objectMapper.createObjectNode();
        editorNode.put("id", "canvas");
        editorNode.put("resourceId", "canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace",
                "http://b3mn.org/stencilset/bpmn2.0#");
        editorNode.put("stencilset", stencilSetNode);
        repositoryService.addModelEditorSource(id, editorNode.toString().getBytes("utf-8"));

        resp.setHeader("Access-Control-Allow-Origin", "*");
        resultMap.put("modelId", model.getId());
        resultMap.put("modelName", model.getName());
        resultMap.put("decription", model.getMetaInfo());
        return resultMap;
    }


    /**
     * 发布模型为流程定义
     */
    @PostMapping("{modelId}/deployment")
    @ResponseBody
    public Result deploy(@PathVariable("modelId") String modelId) throws Exception {
        Result result = new Result();
        try {
            //获取模型
            Model modelData = repositoryService.getModel(modelId);
            byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());
            repositoryService.getModelEditorSourceExtra(modelId);
            if (bytes == null) {
                result.setCode(Status.FAIL);
                result.setData("模型数据为空，请先设计流程并成功保存，再进行发布。");
                return result;
            }

            JsonNode modelNode = new ObjectMapper().readTree(bytes);

            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            if (model.getProcesses().size() == 0) {
                result.setCode(Status.FAIL);
                result.setData("数据模型不符要求，请至少设计一条主线流程。");
                return result;
            }
            byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            //发布流程
            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment()
                    .name(modelData.getName())
                    .addString(processName, new String(bpmnBytes, "UTF-8"))
                    .deploy();
            modelData.setDeploymentId(deployment.getId());
            repositoryService.saveModel(modelData);
            result.setCode("200");
            result.setData("成功发布！");
        } catch (Exception e) {
            result.setCode("009");
            result.setData("发布失败！");
        }
        return result;
    }


    /**
     * 根据id启动流程
     */
    @PostMapping("/startProcess/{modelId}")
    @ResponseBody
    public Map<String, String> startProcess(@PathVariable("modelId") String modelId){
        Map<String, String> result = new HashMap<String, String>();
        try{
            // 启动流程实例
            String depId = repositoryService.createModelQuery().modelId(modelId).singleResult().getDeploymentId();
            Deployment dep = repositoryService.createDeploymentQuery().deploymentId(depId).singleResult();
            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().deploymentId(dep.getId()).singleResult();
            ProcessInstance pi = runtimeService.startProcessInstanceById(pd.getId());

            List<Task> tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).list();

            result.put("processid", pi.getId());
            result.put("name", tasks.get(0).getName());
            result.put("id", tasks.get(0).getId());
            result.put("taskId", tasks.get(0).getId());
            result.put("success", "1");
        }catch (Exception e){
            logger.error("启动流程失败 modeld为： "+modelId,e);
            result.put("success", "0");
        }
        return result;

    }

    //新职场批量上传
    @PostMapping("/startProcess/{modelId}/{amount}")
    @ResponseBody
    public List<ProcessFlow> startProcessList(@PathVariable("modelId") String modelId, @PathVariable("amount") int amount) throws Exception {
        Map<String, String> result = new HashMap<String, String>();
        List<ProcessFlow> pFlows = new ArrayList<>();
        ProcessFlow proFlow = new ProcessFlow();


        // 启动流程实例
        String depId = repositoryService.createModelQuery().modelId(modelId).singleResult().getDeploymentId();
        Deployment dep = repositoryService.createDeploymentQuery().deploymentId(depId).singleResult();
        ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().deploymentId(dep.getId()).singleResult();
        ProcessInstance pi = runtimeService.startProcessInstanceById(pd.getId());

        //循环上传
        for (int i = 0; i < amount; i++) {
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
            ProcessFlow flow = new ProcessFlow(pi.getId(), tasks.get(0).getName(), tasks.get(0).getId(), tasks.get(0).getId());
            pFlows.add(flow);
        }
        return pFlows;

    }


    /**
     * 根据processInId taskId完成任务
     */
    @PostMapping("/completeTask/{taskID}/{processInstanceId}")
    @ResponseBody
    public Map<String, String> completeTasks(HttpServletResponse response, HttpServletRequest request, @PathVariable("taskID") String taskID, @PathVariable("processInstanceId") String processInstanceId) {

        Map<String, String> resultMap = new HashMap<String, String>();
        ProcessInstance processInstance = null;
        //获取变量值
        Map<String, Object> variables = new HashMap<String, Object>();
        getvariables(variables, request);

        //将校正对的taskId进行完成任务  并返回taskid和taskState
        String listen = request.getParameter("listen");
        List<Task> tasks1 = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        if (tasks1.size() > 0 && !tasks1.get(0).getId().equals(taskID)) {
            if (StringUtils.isNotEmpty(listen)) {
                //质检系统听单时传入的是分单taskID，实际流程是听单。
                List<Task> tasks2 = taskService.createTaskQuery().executionId(tasks1.get(0).getExecutionId()).list();
                String taskDefinitionKey = tasks2.get(tasks2.size() - 1).getTaskDefinitionKey();
                if (StringUtils.isNotEmpty(taskDefinitionKey) && taskDefinitionKey.equals("listen")) {
                    taskID = tasks1.get(0).getId();
                }
                //质检系统听单时传入的是听单taskID，实际流程是审单。
                if (StringUtils.isNotEmpty(taskDefinitionKey) && taskDefinitionKey.equals("audit")) {
                    //直接返回结果
                    resultMap.put("taskId", tasks1.get(0).getId());
                    resultMap.put("taskState", getTaskStates(tasks1.get(0).getTaskDefinitionKey()));
                    return  resultMap;
                }

            }
        }
         //获取信号
        if (request.getParameter("Signal") != null) {
            runtimeService.signalEventReceived(request.getParameter("Signal"));
            //获取下一个流程单例
            processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            resultMap.put("signalComplete", "信号已正确引导流程方向。");
        } else {
            //获取下一个流程单例
            try {
                taskService.complete(taskID, variables);
            } catch (Exception e) {
                logger.info("taskId为" + taskID + "的工作流异常:" + e);
            }

            processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();

        }

        if (processInstance != null) {//流程未结束
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
            for (int i = 0; i < tasks.size(); i++) {//质检不具有双向流程
                resultMap.put("taskId", tasks.get(i).getId());
                if (!"-99".equals(getTaskStates(tasks.get(i).getTaskDefinitionKey())) && !"-1".equals(getTaskStates(tasks.get(i).getTaskDefinitionKey()))) {
                    resultMap.put("taskState", getTaskStates(tasks.get(i).getTaskDefinitionKey()));
                }
            }
        } else {//流程已结束
            resultMap.put("taskComplete", "流程已结束！");
        }

        return resultMap;
    }


    /**
     * 读取带跟踪的图片 高亮图片
     */
    @RequestMapping(value = "/{processInstanceId}/{flag}/showModelGLPicture")
    public void showModelGLPicture(HttpServletResponse response, @PathVariable("processInstanceId") String processInstanceId, @PathVariable("flag") String flag) throws Exception {

        //processInstanceId
//    	Task task1 = taskService.createTaskQuery().taskId(taskId).singleResult();
//        String processInstanceId = task1.getProcessInstanceId();
        //获取历史流程实例
        HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        processEngineConfiguration = processEngine.getProcessEngineConfiguration();
        Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);

        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
        ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());

        List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
        //高亮环节id集合
        List<String> highLightedActivitis = new ArrayList<String>();
        //高亮线路id集合
        List<String> highLightedFlows = getHighLightedFlows(definitionEntity, highLightedActivitList);

        for (HistoricActivityInstance tempActivity : highLightedActivitList) {
            String activityId = tempActivity.getActivityId();
            highLightedActivitis.add(activityId);
        }

        InputStream imageStream = null;
        if ("1".equals(flag)) {
            //中文显示的是口口口，设置字体就好了
            imageStream = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitis,
                    highLightedFlows, "宋体", "宋体", null, null, 1.0);
        } else {
            //单独返回流程图，不高亮显示
            imageStream = diagramGenerator.generateDiagram(bpmnModel, "png", Collections.<String>emptyList(), Collections.<String>emptyList(), "宋体", "宋体", null, null, 1.0);
//        	imageStream = diagramGenerator.generatePngDiagram(bpmnModel);
        }
        // 输出资源内容到相应对象
        byte[] b = new byte[1024];
        int len;
        while ((len = imageStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }
    }

    /**
     * 读取带跟踪的图片 高亮图片
     */
    @RequestMapping(value = "/{taskId}/{flag}/showModelGLTaskPicture")
    public void showModelTaskGLPicture(HttpServletResponse response, @PathVariable("taskId") String taskId, @PathVariable("flag") String flag) throws Exception {

        //processInstanceId
        Task task1 = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task1.getProcessInstanceId();
        //获取历史流程实例
        HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        processEngineConfiguration = processEngine.getProcessEngineConfiguration();
        Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);

        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
        ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());

        List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
        //高亮环节id集合
        List<String> highLightedActivitis = new ArrayList<String>();
        //高亮线路id集合
        List<String> highLightedFlows = getHighLightedFlows(definitionEntity, highLightedActivitList);

        for (HistoricActivityInstance tempActivity : highLightedActivitList) {
            String activityId = tempActivity.getActivityId();
            highLightedActivitis.add(activityId);
        }

        InputStream imageStream = null;
        if ("1".equals(flag)) {
            //中文显示的是口口口，设置字体就好了
            imageStream = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitis,
                    highLightedFlows, "宋体", "宋体", null, null, 1.0);
        } else {
            //单独返回流程图，不高亮显示
            imageStream = diagramGenerator.generateDiagram(bpmnModel, "png", Collections.<String>emptyList(), Collections.<String>emptyList(), "宋体", "宋体", null, null, 1.0);
//        	imageStream = diagramGenerator.generatePngDiagram(bpmnModel);
        }
        // 输出资源内容到相应对象
        byte[] b = new byte[1024];
        int len;
        while ((len = imageStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }
    }


    //获取变量值
    private void getvariables(Map<String, Object> variables, HttpServletRequest request) {
        if (request.getParameter("reLitenerResult") != null) {
            variables.put("listenResult", getReCheckListenResult(request.getParameter("reLitenerResult")));
        }
        if (request.getParameter("litenerResult") != null) {
            variables.put("listenResult", getListenResult(request.getParameter("litenerResult")));
        }
        if (request.getParameter("listenResult") != null) {
            variables.put("listenResult", getListenResult(request.getParameter("listenResult")));
        }
        if (request.getParameter("audit") != null) {
            variables.put("audit", getAudit(request.getParameter("audit")));
        }
        if (request.getParameter("reListener") != null) {
            variables.put("reListener", getReListener(request.getParameter("reListener")));
        }
        if (request.getParameter("appeal") != null) {
            variables.put("appeal", getAppeal(request.getParameter("appeal")));
        }
        if (request.getParameter("chulifangshi") != null) {
            variables.put("ProcessMethod", getChulifangshi(request.getParameter("chulifangshi")));
        }
        if (request.getParameter("toAppeal") != null) {
            variables.put("toAppeal", request.getParameter("toAppeal"));
        }
        if (request.getParameter("toTmr") != null) {
            variables.put("toTmr", request.getParameter("toTmr"));
        }
        if (request.getParameter("yblistenResult") != null) {
            variables.put("ybResults", getybListenResult(request.getParameter("yblistenResult")));
        }
        if (request.getParameter("ybbulu") != null) {
            variables.put("record", getbubulu(request.getParameter("ybbulu")));
        }
        if (request.getParameter("auditResult") != null) {
            variables.put("audit", getauditResult(request.getParameter("auditResult")));
        }
        if (request.getParameter("auditRecord") != null) {
            variables.put("record", getbubulu(request.getParameter("auditRecord")));
        }
        if (request.getParameter("zhenggai") != null) {
            variables.put("zhenggai", getzhenggai(request.getParameter("zhenggai")));
        }
        if (request.getParameter("ybpolicyaudit") != null) {
            variables.put("auditResult", getAudit(request.getParameter("ybpolicyaudit")));
        }
        if (request.getParameter("recheck") != null) {
            variables.put("recheck", getReCheckListen(request.getParameter("recheck")));
        }
        //获取callback变量
        if (request.getParameter("callBack") != null) {
            variables.put("callBack", request.getParameter("callBack"));
        }

    }

    private Object getzhenggai(String zhenggai) {
        //整改合格 1  整改不合格 2
        String chulifangshiString = "";
        if ("1".equals(zhenggai)) {
            chulifangshiString = "合格";
        } else if ("2".equals(zhenggai)) {
            chulifangshiString = "不合格";
        }
        return chulifangshiString;
    }

    private Object getauditResult(String auditResult) {
        String chulifangshiString = "";
        if ("0".equals(auditResult)) {
            chulifangshiString = "通过";
        } else if ("1".equals(auditResult)) {
            chulifangshiString = "退回";
        }
        return chulifangshiString;
    }

    private String getbubulu(String ybbulu) {
        String chulifangshiString = "";
        if ("1".equals(ybbulu)) {
            chulifangshiString = "待补录";
        } else if ("2".equals(ybbulu)) {
            chulifangshiString = "不待补录";
        }
        return chulifangshiString;
    }

    private String getybListenResult(String yblistenResult) {
        //正常发单 0、访后发单 1、禁止发单 2
        String chulifangshiString = "";
        if ("1".equals(yblistenResult)) {
            chulifangshiString = "合格单";
        } else if ("2".equals(yblistenResult)) {
            chulifangshiString = "无需质检";
        } else if ("3".equals(yblistenResult)) {
            chulifangshiString = "不合格单:待整改";
        }
        return chulifangshiString;
    }

    private String getChulifangshi(String chulifangshi) {
        //正常发单 0、访后发单 1、禁止发单 2
        String chulifangshiString = "";
        if ("0".equals(chulifangshi)) {
            chulifangshiString = "正常发单";
        } else if ("1".equals(chulifangshi)) {
            chulifangshiString = "访后发单";
        } else if ("2".equals(chulifangshi)) {
            chulifangshiString = "禁止发单";
        }
        return chulifangshiString;
    }


    //申诉结果转变
    private String getAppeal(String appealCode) {
        String appeal = "";
        if ("1".equals(appealCode)) {
            appeal = "通过";
        } else if ("2".equals(appealCode)) {
            appeal = "不通过";
        }
        return appeal;
    }

    //回听结果转变
    private String getReListener(String reListenerCode) {
        //回访合格” 0、“回访不合格” 1' 、“已退保” 2、“多次联系不上结案” 3
        String reListener = "";
        if ("0".equals(reListenerCode)) {
            reListener = "回访合格";
        } else if ("1".equals(reListenerCode)) {
            reListener = "回访不合格";
        } else if ("2".equals(reListenerCode)) {
            reListener = "已退保";
        } else if ("3".equals(reListenerCode)) {
            reListener = "多次联系不上结案";
        }
        return reListener;
    }

    //听单结果转变2（是否合格）
    private String getReCheckListenResult(String litenerResult) {
        String listen = "";
        if ("0".equals(litenerResult)) {
            listen = "合格";
        } else if ("1".equals(litenerResult)) {
            listen = "记错";
        } else if ("2".equals(litenerResult)) {
            listen = "记错严重违规行为";
        }
        return listen;
    }

    //听单结果转变
    private String getListenResult(String litenerResult) {
        //OK单 0  无需质检单 1  缺点单 2  建议单3 回访单4 回访不计单5
        String listen = "";
        if ("0".equals(litenerResult)) {
            listen = "OK单";
        } else if ("1".equals(litenerResult)) {
            listen = "无需质检单";
        } else if ("2".equals(litenerResult)) {
            listen = "缺点单";
        } else if ("3".equals(litenerResult)) {
            listen = "建议单";
        } else if ("4".equals(litenerResult)) {
            listen = "回访单";
        } else if ("5".equals(litenerResult)) {
            listen = "回访不计单";
        } else if ("9".equals(litenerResult)) {
            listen = "禁发单";//禁发单是新职场BOCOM和CITIC让添加的听单结果
        } else if ("6".equals(litenerResult)) {
            listen = "禁发单";//禁发单是DTC让添加的听单结果，清除建议单，cxl
        }
        return listen;
    }

    //质检状态转变
    public String getTaskStates(String taskDefinitionKey) {
        //质检状态 已分组待分配 0  已分配待听单 1 已听单待审单2  已审单待跟进3
        // 已审单不回访4 (即建议单缺点单 )   已审单重回听5          已回访待回听6   4审单不回访直接走完成
        // 已回听重回访7             申请销单8 完成9

        String rs = "-99";
        if ("policyImport".equals(taskDefinitionKey)) {
            rs = "-1";
        } else if ("distribution".equals(taskDefinitionKey)) {
            rs = "0";
        } else if ("listen".equals(taskDefinitionKey)) {
            rs = "1";
        } else if ("audit".equals(taskDefinitionKey)) {
            rs = "2";
        } else if ("tmr".equals(taskDefinitionKey)) {
            rs = "3";
        } else if ("tms".equals(taskDefinitionKey)) {
            rs = "3";
        } else if ("reListen".equals(taskDefinitionKey)) {
            rs = "6";
        } else if ("appeal".equals(taskDefinitionKey)) {
            rs = "8";
        } else if ("complete".equals(taskDefinitionKey)) {
            rs = "9";
        } else if ("auditRelisten".equals(taskDefinitionKey)) {
            rs = "5";
        } else if ("auditOk".equals(taskDefinitionKey)) {
            rs = "4";
        } else if ("ReListenReTmr".equals(taskDefinitionKey)) {
            rs = "7";
        } else if ("tmrOrtms".equals(taskDefinitionKey)) {
            rs = "3";
            //质检状态  '待分组 0  已分组待分配 1 已分配待质检 2已质检待审单 3
            // 已审单待补录 4 已审单待重检 5已补录待回检 6 已回检重补录 7  完成8'
        } else if ("YBPolicyImport".equals(taskDefinitionKey)) {
            rs = "0";
        } else if ("YBDistribution".equals(taskDefinitionKey)) {
            rs = "1";
        } else if ("YBQuality".equals(taskDefinitionKey)) {
            rs = "2";
        } else if ("YBAudit".equals(taskDefinitionKey)) {
            rs = "3";
        } else if ("YBRecord".equals(taskDefinitionKey)) {
            rs = "4";
        } else if ("YbReAuditQuality".equals(taskDefinitionKey)) {
            rs = "5";
        } else if ("YBReQuality".equals(taskDefinitionKey)) {
            rs = "6";
        } else if ("YbReRecord".equals(taskDefinitionKey)) {
            rs = "7";
        } else if ("Ybcomplete".equals(taskDefinitionKey)) {
            rs = "8";
        } else if ("filter".equals(taskDefinitionKey)) {//复检中待筛选状态
            rs = "14";
        } else if ("closure".equals(taskDefinitionKey)) {//复检中已审单待结案状态
            rs = "15";
        }
        return rs;
    }

    //审单结果转变
    private String getAudit(String auditCode) {
        String audit = "";
        if ("0".equals(auditCode)) {
            audit = "通过";
        } else {
            audit = "不通过";
        }
        return audit;
    }

    //复检质检结果转变
    private String getReCheckListen(String listenResult) {
        String listen = "";
        if ("0".equals(listenResult)) {
            listen = "OK单";
        } else if ("1".equals(listenResult)) {
            listen = "建议单";
        } else if ("2".equals(listenResult)) {
            listen = "无需质检单";
        } else if ("3".equals(listenResult)) {
            listen = "缺点单";
        } else if ("4".equals(listenResult)) {
            listen = "访后单";
        } else if ("5".equals(listenResult)) {
            listen = "严重违规行为";
        } else if ("9".equals(listenResult)) {
            listen = "回访不计单";
        }else if ("7".equals(listenResult)) {
            listen = "禁发单";
        }
        return listen;
    }

    /**
     * 获取需要高亮的线
     *
     * @param processDefinitionEntity
     * @param historicActivityInstances
     * @return
     */
    private List<String> getHighLightedFlows(
            ProcessDefinitionEntity processDefinitionEntity,
            List<HistoricActivityInstance> historicActivityInstances) {
        List<String> highFlows = new ArrayList<String>();// 用以保存高亮的线flowId
        for (int i = 0; i < historicActivityInstances.size() - 1; i++) {// 对历史流程节点进行遍历
            ActivityImpl activityImpl = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i)
                            .getActivityId());// 得到节点定义的详细信息
            List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();// 用以保存后需开始时间相同的节点
            ActivityImpl sameActivityImpl1 = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i + 1)
                            .getActivityId());
            // 将后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                HistoricActivityInstance activityImpl1 = historicActivityInstances
                        .get(j);// 后续第一个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances
                        .get(j + 1);// 后续第二个节点
                if (activityImpl1.getStartTime().equals(
                        activityImpl2.getStartTime())) {
                    // 如果第一个节点和第二个节点开始时间相同保存
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity
                            .findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                } else {
                    // 有不相同跳出循环
                    break;
                }
            }
            List<PvmTransition> pvmTransitions = activityImpl
                    .getOutgoingTransitions();// 取出节点的所有出去的线
            for (PvmTransition pvmTransition : pvmTransitions) {
                // 对所有的线进行遍历
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition
                        .getDestination();
                // 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }

    @Override
    public Object getOne(@PathVariable("id") String id) {
        Model model = repositoryService.createModelQuery().modelId(id).singleResult();
        return ToWeb.buildResult().setObjData(model);
    }

    @Override
    public Object getList(@RequestParam(value = "rowSize", defaultValue = "1000", required = false) Integer rowSize, @RequestParam(value = "page", defaultValue = "1", required = false) Integer page) {
        List<Model> list = repositoryService.createModelQuery().listPage(rowSize * (page - 1)
                , rowSize);
        long count = repositoryService.createModelQuery().count();

        return ToWeb.buildResult().setRows(
                ToWeb.Rows.buildRows().setCurrent(page)
                        .setTotalPages((int) (count / rowSize + 1))
                        .setTotalRows(count)
                        .setList(list)
                        .setRowSize(rowSize)
        );
    }

    public Object deleteOne(@PathVariable("id") String id) {
        repositoryService.deleteModel(id);
        return ToWeb.buildResult().refresh();
    }

    @Override
    public Object postOne(@RequestBody Model entity) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object putOne(@PathVariable("id") String s, @RequestBody Model entity) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object patchOne(@PathVariable("id") String s, @RequestBody Model entity) {
        throw new UnsupportedOperationException();
    }


//=====================淘汰方法留用==========================
//注释掉 换成统一方法调取
//    /**
//     * 质检单导入
//     */
//    @PostMapping("policyImport/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> policyImport(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//            resultMap.put("taskId",tasks.get(i).getId());
//        }
//        return resultMap;
//    }
//
//    /**
//     * 质检单分配
//     */
//    @PostMapping("policyDistribution/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> policyDistribution(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//            resultMap.put("taskId",tasks.get(i).getId());
//        }
//        return resultMap;
//    }
//
//    /**
//     * 质检单听单
//     */
//    @PostMapping("policyListen/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> policyListen(HttpServletResponse response ,HttpServletRequest request,@PathVariable("taskID")String taskID){
//        String litenerResultCode = request.getParameter("litenerResult");
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        Map<String, Object> variables = new HashMap<String, Object>();//增加变量 即听单结果
//        variables.put("listenResult", getListenResult(litenerResultCode));
//        taskService.complete(taskID,variables);
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//            resultMap.put("taskId",tasks.get(i).getId());
//        }
//        return resultMap;
//    }
//
//    /**
//     * 质检单审单
//     */
//    @PostMapping("policyAudit/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> policyAudit(HttpServletResponse response ,HttpServletRequest request,@PathVariable("taskID")String taskID){
//        String litenerResultCode = request.getParameter("litenerResult");
//        String auditCode = request.getParameter("audit");
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        Map<String, Object> variables = new HashMap<String, Object>();//增加变量 即听单结果
//        variables.put("listenResult", getListenResult(litenerResultCode));
//        variables.put("audit", getAudit(auditCode));
//        taskService.complete(taskID,variables);
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//            resultMap.put("taskId",tasks.get(i).getId());
//        }
//        return resultMap;
//    }
//
//
//
//    /**
//     * 已审单不回访
//     */
//    @PostMapping("policyAuditOk/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> policyAuditOk(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {//不会有下一步了
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//        }
//        if(tasks.size()==0){
//            resultMap.put("taskStates",(short)9);
//        }
//        return resultMap;
//    }
//
//    /**
//     * 已审单待跟进
//     */
//    @PostMapping("policyTmr/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> policyTmr(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//        }
//        if(tasks.size()==0){
//            resultMap.put("taskStates",(short)9);
//        }
//        return resultMap;
//    }
//
//    /**
//     * 已审单不回访
//     */
//    @PostMapping("policyComplete/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> policyComplete(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {//不会有下一步了
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//        }
//        if(tasks.size()==0){
//            resultMap.put("taskStates",(short)4);
//        }
//        return resultMap;
//    }
//
//    /**
//     * 质检单 已审单待回听
//     */
//    @PostMapping("listenerReturn/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> listenerReturn(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        String litenerResult = "缺点单";
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//        }
//        if(tasks.size()==0){
//            resultMap.put("taskStates",(short)9);
//        }
//        return resultMap;
//    }
//
//    /**
//     * 质检单 已回听重回访或者完成
//     */
//    @PostMapping("listenerReturnNo/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> policyTmrOrComplete(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        Boolean reListener  = true;
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        Map<String, Object> variables = new HashMap<String, Object>();//增加变量
//        variables.put("reListener", reListener);
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//        }
//        if(tasks.size()==0){
//            resultMap.put("taskStates",(short)9);
//        }
//        return resultMap;
//    }
//
//    /**
//     * 已审单待跟进
//     */
//    @PostMapping("policyTms/completeTask{taskID}/")
//    @ResponseBody
//    public Map<String,Object> policyTms(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//        }
//        if(tasks.size()==0){
//            resultMap.put("taskStates",(short)9);
//        }
//        return resultMap;
//    }
//
//    /**
//     * 申诉处理
//     */
//    @PostMapping("policyAppeal/completeTask/{taskID}")
//    @ResponseBody
//    public Map<String,Object> policyAppeal(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        Boolean appeal = true;
//        Boolean toTmr = true;
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        Map<String, Object> variables = new HashMap<String, Object>();//增加变量
//        variables.put("appeal", appeal);
//        variables.put("toTmr", toTmr);
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//        }
//        if(tasks.size()==0){
//            resultMap.put("taskStates",(short)9);
//        }
//
//        return resultMap;
//    }
//
//    /**
//     * 已完成
//     */
//    @PostMapping("policyAll/completeTask{taskID}/")
//    @ResponseBody
//    public Map<String,Object> policyAll(HttpServletResponse response ,@PathVariable("taskID")String taskID){
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String processInstanceId = taskService.createTaskQuery().taskId(taskID).singleResult().getProcessInstanceId();//获取流程id
//        Task singleResult = taskService.createTaskQuery().taskId(taskID).singleResult();//获取任务
//        taskService.complete(taskID);//完成任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();//查询接下来应该走哪些步骤
//        Short taskStates = -1;//返回的质检状态
//        for(int i=0; i<tasks.size(); i++) {
//            //获取接下来任务的taskStates 因为都是单向去走，所以只会有一个任务
////            System.out.println("接下来的流程任务：" + tasks.get(i).getName()+"--"+tasks.get(i).getId());
//            String taskDefinitionKey = tasks.get(i).getTaskDefinitionKey();
//            taskStates = getTaskStates(taskDefinitionKey);
//            resultMap.put("taskStates",taskStates);
//        }
//        if(tasks.size()==0){
//            resultMap.put("taskId","-1");
//        }
//        return resultMap;
//    }
//

//    /**
//     * 根据id生成图片(此方法生产的图片不清晰)
//     */
//    @GetMapping("/{id}/showModelPicture")
//    public void showModelPicture(HttpServletResponse response ,@PathVariable("id")String modelId)throws Exception{
//        RepositoryService repositoryService=processEngine.getRepositoryService();
//
//        Model modelData = processEngine.getRepositoryService().getModel(modelId);
//        ObjectNode modelNode = null;
//        try {
//            modelNode = (ObjectNode) new ObjectMapper()
//                    .readTree(repositoryService.getModelEditorSource(modelData.getId()));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
//        ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
//        InputStream inputStream = processDiagramGenerator.generateDiagram(model,
//                "png",
//                Collections.<String>emptyList());
//
//        OutputStream out = response.getOutputStream();
//        for (int b = -1; (b = inputStream.read()) != -1; ) {
//            out.write(b);
//        }
//        out.close();
//        inputStream.close();
//    }
}